<template>
    <div class="login">
        <div class="title">登录页</div>
        <van-form @submit="login">
            <van-field
                v-model="formData.phone"
                name="用户名"
                placeholder="用户名"
                :rules="[{ required: true, pattern:/^1[3-9]\d{9}$/, message: '请填写用户名' }]"
            />
            <van-field
                v-model="formData.pass"
                type="password"
                name="密码"
                placeholder="密码"
                :rules="[{ required: true, pattern:/^\d{4}$/,  message: '请填写密码' }]"
            />
            <div style="margin: 16px;">
                <van-button round block type="info" native-type="submit">提交</van-button>
            </div>
        </van-form>
            
        <div class="goregister" @click="$router.push('/register')">
            <span>去注册</span>
        </div>
    </div>
</template>

<script>
import { Toast } from 'vant';
// 导入封装好的axios
import {user_login} from '../utils/api'
export default {
  data(){
    return {
      formData:{
        phone:'',
        pass:''
      }
    }
  },
    methods:{
        login(){
                // 发起登录请求
                user_login(this.formData).then((res)=>{
                    if(res.data.code==200){
                        // 保存用户信息，token
                        localStorage.setItem('token',res.data.token);
                        localStorage.setItem('userinfo',JSON.stringify(res.data.userinfo))
                        Toast.success('登录成功')
                        // 请求当前用户的收藏列表
                        this.$store.dispatch('request_favlist') 
                        // 请求用户的购物车列表
                        this.$store.dispatch('request_shopCart')
                        // 自动跳转到首页
                        this.$router.push('/');
                    }else{
                        Toast.fail('登录失败')
                    }
                })
            }
        },
    }
</script>

<style lang="scss" scoped>
    .login{
        margin: 50px 20px;
    }
    .login .title{
        font-weight: bold;
        text-align: center;
        line-height: 40px;
    }
    
    .login .input-box{
        height: 40px;
        border: 1px solid #ccc;
        border-radius: 20px;
        padding-left: 20px;
        box-sizing: border-box;
        outline: none;
        width: 100%;
        margin: 20px 0;
    }
  
    .van-field{
        margin: 40px 0;
        border: 1px solid #ccc;
        border-radius: 20px;
    }
    .goregister{
        width: 100px;
        height: 50px;
        margin: auto;
    }
</style>